<template>
  <el-card body-class="server-list" class="column-left" ref="elCardRefTable">
    <template #header>
      <div class="card-header table-header">
        <div class="small-header">
          <el-select
            v-model="value"
            placeholder="Select"
            size="small"
            style="width: 240px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div>
          <svg-icon
            v-for="(item, index) in leftTool"
            class-name="iconfont"
            @click="handleTool(index)"
            :key="item.id"
            :title="item.label"
            :icon-class="item.icon"
          />
          <el-popover placement="top" :width="200" trigger="click">
            <template #reference>
              <svg-icon
                class-name="iconfont"
                @click="handleTool(index)"
                key="item.id"
                title="item.label"
                icon-class="ditufuwei"
              />
            </template>
            <el-checkbox-group v-model="checkList">
              <el-checkbox label="Option A" value="Value A" />
              <el-checkbox label="Option B" value="Value B" />
              <el-checkbox label="Option C" value="Value C" />

              <el-checkbox label="disabled" value="Value disabled" disabled />
              <el-checkbox
                label="selected and disabled"
                value="Value selected and disabled"
                disabled
              />
            </el-checkbox-group>
          </el-popover>

          <svg-icon
            class-name="iconfont error"
            @click="emits('changeHide')"
            icon-class="error"
          />
        </div>
      </div>
    </template>
    <el-auto-resizer>
      <template #default="{ height, width }">
        <el-table-v2
          :row-event-handlers="{
            onClick: handleRowClick,
            onContextmenu: handleContextMenu,
            onDblclick: handleDbRowClick,
          }"
          :columns="columns"
          :row-class="rowClassName"
          :data="data"
          :width="width"
          :height="height"
          :header-height="30"
          :row-height="30"
          fixed
        >
        </el-table-v2>
      </template>
    </el-auto-resizer>
  </el-card>
  <ContextMenu
    :menuItems="componentAMenuItems"
    v-model:visible="menuFlag"
    ref="contextMenuRef"
  />
</template>

<script setup>
import { defineEmits } from "vue";
import { defineExpose } from "vue";
import ContextMenu from "../common/ContextMenu.vue";
import { listTableField, listTableData } from "../../../api/postmap/maptable";

const menuFlag = ref(false);
const emits = defineEmits(["changeHide"]);
const data = ref([]);
var columns = ref([]);
const checkList = ref(["Value selected and disabled", "Value A"]);
/**
 *
 * @param e
 */
const showTableData = (e) => {
  var query = e;
  query = {
    layerId: "12345680",
    tableId: "1860610072491765761",
    storeId: "1855274826796576771",
  };
  // columns=[{key:"tableName",dataKey:"tableName",title:"tableName",width:100}]
  listTableData(query).then((res) => {
    columns.value = res.data.fields;
    data.value = res.data.rows;
    // console.info(res);
  });
};

const generateColumns = async (e) => {
  var query = {
    layerId: "12345680",
    tableId: "1860610072491765761",
    storeId: "1855274826796576771",
  };
  await listTableField(query).then((res) => {
    columns.value = res.rows;
  });
};

// const columns = generateColumns(10);
// const data = generateData(columns, 1000);
// 用于记录当前点击行的索引，初始化为 -1 表示没有行被点击
const currentRowIndex = ref([]);

// row-class-name 绑定的函数，根据行索引判断是否添加高亮类名
const rowClassName = ({ row, rowIndex }) => {
  if (currentRowIndex.value.indexOf(rowIndex) > -1) {
    return "highlight-row"; // 返回高亮的类名，这里定义为 highlight-row，可自行修改
  }
  return "";
};

// 定义一个方法，用于处理行点击事件，更新当前点击行的索引
const handleRowClick = (row, rowIndex) => {
  var index = currentRowIndex.value.indexOf(row.rowIndex);
  if (index > -1) {
    currentRowIndex.value.splice(index, 1);
    return;
  }
  currentRowIndex.value.push(row.rowIndex);
};
//右键列表菜单
const componentAMenuItems = [
  {
    label: "闪烁要素",
    icon: "huanjingshezhi",
    // children: [{ label: "二级菜单2-1", icon: "huanjingshezhi" }],
  },
  {
    label: "平移到要素",
    icon: "huanjingshezhi",
    // children: [
    //   {
    //     label: "二级菜单1-1",
    //     icon: "huanjingshezhi",
    //   },
    //   { label: "二级菜单1-2", icon: "huanjingshezhi" },
    // ],
  },
  {
    label: "缩放到要素",
    icon: "huanjingshezhi",
    // children: [
    //   {
    //     label: "二级菜单1-1",
    //     icon: "huanjingshezhi",
    //   },
    //   { label: "二级菜单1-2", icon: "huanjingshezhi" },
    // ],
  },
];
//左侧工具栏状态
const leftToolStatus = ref(-1);
//左侧工具栏
const leftTool = [
  {
    id: 1,
    icon: "ditufuwei",
    label: "刷新",
  },
  {
    id: 2,
    icon: "tianjiatukuangfangan",
    label: "过滤",
  },
  {
    id: 2,
    icon: "tianjiatukuangfangan",
    label: "全选",
  },
  {
    id: 2,
    icon: "tianjiatukuangfangan",
    label: "反选",
  },
  {
    id: 2,
    icon: "tianjiatukuangfangan",
    label: "平移到所选记录",
  },
  {
    id: 2,
    icon: "tianjiatukuangfangan",
    label: "缩放到所选记录",
  },
];

const value = ref("");

const options = [
  {
    value: "Option1",
    label: "Option1",
  },
  {
    value: "Option2",
    label: "Option2",
  },
  {
    value: "Option3",
    label: "Option3",
  },
  {
    value: "Option4",
    label: "Option4",
  },
  {
    value: "Option5",
    label: "Option5",
  },
];
const contextMenuRef = ref(null);

//双击事件
const handleDbRowClick = () => {
  alert("双击事件");
};
//获取鼠标位置
const handleContextMenu = ({ row, column, event }) => {
  // 阻止默认的右键菜单行为
  event.preventDefault();
  // 获取右键菜单组件实例并设置其显示位置为鼠标点击位置
  const context = contextMenuRef.value;
  menuFlag.value = true;
  let x = event.clientX;
  let y = event.clientY;

  // 获取页面可视区域的宽度和高度

  const pageWidth = document.documentElement.clientWidth;
  const pageHeight = document.documentElement.clientHeight;
  nextTick(() => {
    // 获取右键菜单自身的宽度和高度（这里假设右键菜单已经渲染完成，可以获取到准确的尺寸）
    const menuWidth = context.$el.offsetWidth;
    const menuHeight = context.$el.offsetHeight;
    // 判断右键菜单是否超出页面右侧边界，如果超出则将其左侧位置调整为边界内
    if (x + menuWidth > pageWidth) {
      x = pageWidth - menuWidth;
    }

    // 判断右键菜单是否超出页面底部边界，如果超出则将其顶部位置往上调整
    if (y + menuHeight > pageHeight) {
      y = Math.max(0, y - menuHeight);
    }

    context.$el.style.left = x + "px";
    context.$el.style.top = y + "px";
  });
};
//关闭表格
const closeTable = () => {
  emits("changeHide");
};

const elCardRefTable = ref(null);
const isDOM = (e) => {
  e.preventDefault();
  const target = e.target;
  var isUnderTopElement = elCardRefTable.value.$el.contains(target);
  if (!isUnderTopElement) {
    menuFlag.value = false;
  }
};
const wClick = (e) => {
  const target = e.target;
  const toolA = contextMenuRef.value.$el;
  const isInsideTool = toolA && toolA.contains(target);
  if (!isInsideTool) {
    menuFlag.value = false;
  }
};
onMounted(() => {
  window.addEventListener("click", wClick);
  // 监听整个窗口的右键点击事件
  window.addEventListener("contextmenu", isDOM);

  //
  showTableData({});
});
onUnmounted(() => {
  window.removeEventListener("click", wClick);
  window.removeEventListener("contextmenu", isDOM);
});
// 使用 defineExpose 将方法暴露给父组件
defineExpose({
  showTableData,
});
</script>
<style >
.highlight-row {
  background: #0074b7;
  color: #fff;
}
</style>

<style lang="scss" scoped>
:deep(.el-table--default .el-table__cell) {
  padding: 0;
}

:deep(.el-table__header-wrapper th) {
  height: 30px !important;
}
:deep(.el-table-v2__row:hover) {
  background: #0074b7;
  color: #fff;
}
:deep(.el-table-v2__row) {
  cursor: pointer;
}

.iconfont {
  width: 24px;
  height: 24px;
  font-size: 24px;
  cursor: pointer;
}
.error {
  margin-left: 12px;
}

.center-header {
  width: calc(100% - 40px);
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 9;
  height: 40px;
  border: 1px solid #bababaa6;
  border-radius: 4px;
  align-items: center;
  margin-left: 10px;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
}

.small-header {
  height: 30px;
  align-items: center;
  overflow: hidden;

  :deep(.el-button.is-circle) {
    width: 25px;
    height: 25px;
  }
}

.column-left {
  width: 100%;
  height: 100%;
  position: relative;
}

.server-list {
  height: calc(100% - 40px);
  flex: 1;
  overflow: auto;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-card__header) {
  padding: 5px !important;
  max-height: 40px !important;
  min-height: 40px !important;
}

:deep(.el-card__body) {
  height: calc(100% - 40px);
  flex: 1;
  overflow: auto;
  padding: 5px 10px 10px 10px !important;
}
</style>
